package com.ptu.spzx.gateway.filter;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ptu.spzx.gateway.properties.UserWhiterProperties;
import com.ptu.spzx.gateway.util.JwtUtil;
import com.ptu.spzx.gateway.util.RedisCache;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;  //过滤器的优先级
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserWhiterProperties userWhiterProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher(); //路径匹配

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getURI().getPath();
        if(isWhitePath(requestPath)){
            return chain.filter(exchange);
        }
        String token="";
        //请求头获取token
        List<String> tokenList = request.getHeaders().get("Authorization");
        if(tokenList!=null){
            token = tokenList.get(0);
        }
        if(StringUtils.isEmpty(token)){
            System.out.println("第一层检验");
            return out(response,ResultCodeEnum.LOGIN_AUTH);
        }
        //解析token获取其中的userId
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            System.out.println("第二层检验");
            //token超时
            e.printStackTrace();
            return out(response,ResultCodeEnum.LOGIN_AUTH);
        }
        String userId = claims.getSubject();
        Object cacheObject = redisCache.getCacheObject("user:login" + userId);
        System.out.println(cacheObject);
        System.out.println(userId);
        if(Objects.isNull(cacheObject)){
            System.out.println("第三层检验");
            return out(response,ResultCodeEnum.LOGIN_AUTH);
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    // 判断是否是白名单
    private boolean isWhitePath(String requestPath){
        for (String whitePath: userWhiterProperties.getNoAuthUrls()) {
            if(antPathMatcher.match(whitePath, requestPath)){
                return true;
            }
        }
        return false;
    }

}
